/*
 * Copyright 2010 Yaroslav Klymko aka t3hnar
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ua.t3hnar.io.serializer.handlers;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.*;

/**
 * @author Yaroslav Klymko aka t3hnar
 */
public class FieldHandlersProvider {
// ------------------------------ FIELDS ------------------------------

    private static final Log LOG = LogFactory.getLog(FieldHandlersProvider.class);

    private final Map<String, FieldHandler> handlers = Collections.synchronizedMap(new HashMap<String, FieldHandler>(2));

// -------------------------- STATIC METHODS --------------------------

    public static FieldHandlersProvider getInstance() {
        return InstanceHolder.INSTANCE;
    }

// --------------------------- CONSTRUCTORS ---------------------------

    FieldHandlersProvider() {
    }

// -------------------------- OTHER METHODS --------------------------

    public void addHandler(final FieldHandler handler) {
        LOG.debug("Adding handler: " + handler);
        if (handler == null) {
            throw new IllegalArgumentException("Handler is null");
        }
        this.handlers.put(handler.getName(), handler);
    }

    public FieldHandler getHandler(final String key) {
        LOG.debug("Retrieving handler; key: " + key);
        if (key == null) {
            throw new IllegalArgumentException("Key is null");
        }
        return this.handlers.get(key);
    }

    public List<FieldHandler> handlers() {
        LOG.debug("Retrieving all handlers");
        final ArrayList<FieldHandler> list = new ArrayList<FieldHandler>(handlers.values());
        return Collections.unmodifiableList(list);
    }

// -------------------------- INNER CLASSES --------------------------

    private static final class InstanceHolder {

        private static final FieldHandlersProvider INSTANCE = new FieldHandlersProvider();

        static {
            LOG.debug("Loading default handlers");
            INSTANCE.addHandler(new InputStreamHandler());
            INSTANCE.addHandler(new BlobHandler());
        }

        private InstanceHolder() {
        }
    }
}
